/*
 * @Author: Zhouhai 497675647@qq.com
 * @Date: 2022-09-22 16:37:16
 * @LastEditors: zhouhai zhouhaib@yonyou.com
 * @LastEditTime: 2025-03-04 11:45:08
 */
import { RouteObject, useRoutes } from 'react-router-dom';

// routes
import MainRoutes,{LayoutRoutes} from './MainRoutes';
import { useStore } from '@/store';
import { Suspense, useEffect, useState } from 'react';
import React from 'react';
import { MenuDomain } from '@/type.d/system';
import { ErrorBoundary } from './ErrorBoundary';

// ==============================|| ROUTING RENDER ||============================== //

export default function ThemeRoutes() {

    const { userStore } = useStore();
    const [routes, setRoutes] = useState<RouteObject[]>([]);

    useEffect(() => {
        
        if (userStore.menus && userStore.menus.length > 0) {
            //只要菜单，按钮不要
            const menus: MenuDomain[] = filterMenus(userStore.menus);
            if (menus && menus.length > 0) {
                const dbrouters = menus.map((item) => {
                    // 动态导入组件
                    return {
                        path: item.path,
                        element: lazyLoad(item.component || ''),
                        auth: true
                    }
                })

                let newLayoutRoutes = {...LayoutRoutes}
                Array.prototype.push.apply(newLayoutRoutes.children, dbrouters);
                let newAllRouters = MainRoutes.concat(newLayoutRoutes as any);
                setRoutes(newAllRouters)
            } else {
                let newAllRouters = MainRoutes.concat(LayoutRoutes as any);
                setRoutes(newAllRouters)
            }

        } else {
            let newAllRouters = MainRoutes.concat(LayoutRoutes as any);
            setRoutes(newAllRouters)
        }

    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [userStore.menus]);





    /**
     * 根据url加载组件
     * @param moduleName 
     * @returns 
     */
    const lazyLoad = (moduleName: string) => {
        let Component = React.lazy(() => import(`@/pages/${moduleName}`));

        return <ErrorBoundary fallback={DefaultComponent(moduleName)}>
            <Suspense fallback={<div>Loading...</div>}>
                <Component />
            </Suspense>
        </ErrorBoundary>
            
    }

    // 定义默认组件
    const DefaultComponent = (moduleName: string) => {
        return <div>{`Failed to load the ${moduleName}. Please try check.`}</div>;
    };

    /**
     * 过滤数据，只有菜单类型是C的才有路由地址
     * @param allmenus 
     * @returns 
     */
    const filterMenus: (allmenus: MenuDomain[]) => MenuDomain[] = (allmenus) => {

        const menus: MenuDomain[] = [];
        if (allmenus && allmenus.length > 0) {
            allmenus.forEach((item) => {
                if (item.menuType === 'C' && item.component) {
                    menus.push(item)
                }
                if (item.children && item.children.length > 0) {
                    Array.prototype.push.apply(menus, filterMenus(item.children));
                }
            })
        }
        return menus;
    }

    
    return useRoutes(routes);
}
